import Foundation
import CoreData

struct WaterIntake: Identifiable {
    var id = UUID()
    var date: Date
    var amount: Double
    var goal: Double
}

class WaterIntakeStore: ObservableObject {
    @Published var intakes: [WaterIntake] = []
    
    init() {
        // 默认情况下，初始化时加载示例数据
        loadSampleData()
    }
    
    // 添加新的饮水记录
    func addIntake(amount: Double, goal: Double) {
        let newIntake = WaterIntake(date: Date(), amount: amount, goal: goal)
        intakes.append(newIntake)
        // 这里将来会连接到CoreData
    }
    
    // 获取今日总饮水量
    func getTodayTotal() -> Double {
        let today = Calendar.current.startOfDay(for: Date())
        return intakes
            .filter { Calendar.current.isDate($0.date, inSameDayAs: today) }
            .reduce(0) { $0 + $1.amount }
    }
    
    // 加载示例数据
    func loadSampleData() {
        let calendar = Calendar.current
        let today = Date()
        let goal = 2000.0 // 2000毫升
        
        // 清除当前数据
        intakes.removeAll()
        
        // 添加今天的记录
        addSampleIntake(date: today, amount: 250, goal: goal)
        addSampleIntake(date: today.addingTimeInterval(-2 * 3600), amount: 300, goal: goal) // 2小时前
        addSampleIntake(date: today.addingTimeInterval(-5 * 3600), amount: 200, goal: goal) // 5小时前
        
        // 添加过去6天的记录
        for dayOffset in 1...6 {
            if let date = calendar.date(byAdding: .day, value: -dayOffset, to: today) {
                // 每天添加2-4条随机记录
                let recordCount = Int.random(in: 2...4)
                var dailyTotal = 0.0
                
                for _ in 1...recordCount {
                    // 随机时间
                    let randomHour = Int.random(in: 8...20) // 8am到8pm之间
                    let randomMinute = Int.random(in: 0...59)
                    var components = calendar.dateComponents([.year, .month, .day], from: date)
                    components.hour = randomHour
                    components.minute = randomMinute
                    
                    if let recordDate = calendar.date(from: components) {
                        // 随机饮水量 (150-500毫升)
                        let amount = Double(Int.random(in: 15...50) * 10)
                        addSampleIntake(date: recordDate, amount: amount, goal: goal)
                        dailyTotal += amount
                    }
                }
                
                // 确保至少有一天达到目标
                if dayOffset == 2 && dailyTotal < goal {
                    if let bonusDate = calendar.date(bySettingHour: 21, minute: 0, second: 0, of: date) {
                        addSampleIntake(date: bonusDate, amount: goal - dailyTotal + 50, goal: goal)
                    }
                }
            }
        }
    }
    
    // 辅助方法：添加示例数据
    private func addSampleIntake(date: Date, amount: Double, goal: Double) {
        let intake = WaterIntake(id: UUID(), date: date, amount: amount, goal: goal)
        intakes.append(intake)
    }
} 